<template>
  <div :hidden="!modalData.visible" ref="modalRef" :style="`position: fixed;top: ${modalData.top}px;left: ${modalData.left}px;width: 900px;z-index: 9999;
         border-radius: 4px;
         background: white;
         padding: 8px;
         box-shadow: 0 0 4px 4px rgba(0, 0, 0, 0.1);z-index: 999`">
    <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;cursor: move"
         @mousedown="mouseStart" @mousemove="mouseMove">
      <span style="font-size: 18px;font-weight: 600">估价参考</span>
      <CloseOutlined @click="hideModal" style="font-size: 18px;cursor: pointer;z-index: 999" />
    </div>

    <div style="display: flex;flex-direction: row;margin-top: 16px">

      <!--  用户评估详情-->
      <div style="flex: 1">
        <h3>用户评估详情</h3>
        <template v-if="orderDetail.orderWay===1">
          <div>
            <span style="width: 100px;display: inline-block;">下单机型：</span>
            <span>{{ evaluateDetail.modelName }}</span>
          </div>
          <div>
            <span style="width: 100px;display: inline-block;">预估回收价格：</span>
            <span style="color: #FA3131">￥{{ evaluateDetail.mrp }}</span>
          </div>
          <a-divider></a-divider>
          <div style="max-height: 400px;overflow-y: scroll">
            <div v-for="question in evaluateDetail.evalContent">
              <div>
                <b>{{ question['qName'] }}</b>
              </div>
              <div v-for="option in question.options" style="padding-left: 32px">{{ option.oName }}</div>
            </div>
          </div>
        </template>
        <template v-else>
          手机 X{{orderDetail.phoneNum}} 平板 X{{orderDetail.padNum}}
        </template>
      </div>

      <!--  估价-->
      <div style="margin-left: 24px;flex: 1">
        <h3>估价</h3>
        <a-row class="row">
          <a-col :span="5" class="rowLabel">品牌</a-col>
          <a-col :span="10">
            <a-select v-model:value="evaluateData.brandId" allowClear placeholder="选择品牌" style="width: 160px;"
                      @change="queryModel">
              <a-select-option v-for="option in brandOptions" :value="option.id">{{ option.brandName }}</a-select-option>
            </a-select>
          </a-col>
        </a-row>
        <a-row class="row">
          <a-col :span="5" class="rowLabel">品类</a-col>
          <a-col :span="10">
            <a-select v-model:value="evaluateData.category" allowClear placeholder="选择品类" style="width: 160px"
                      @change="queryModel">
              <a-select-option value="1">手机</a-select-option>
              <a-select-option value="2">平板</a-select-option>
            </a-select>
          </a-col>
        </a-row>
        <a-row class="row">
          <a-col :span="5" class="rowLabel">型号</a-col>
          <a-col :span="10">
            <a-select v-model:value="evaluateData.modelId" @change="modelChange"
                      :field-names="{label: 'modelName',value: 'id'}"
                      :filter-option="filterModelOption"
                      :options="modelOptions"
                      allowClear placeholder="选择型号" show-search style="width: 160px">
            </a-select>
          </a-col>
        </a-row>
        <a-row class="row">
          <a-col :span="5" class="rowLabel">预估价格</a-col>
          <a-col :span="10">
            <b style="color: #f50;font-size: 16px">￥{{ evaluateData.appraiseValue }}</b>
          </a-col>
          <a-col :span="9">
            <ZTooltip text-align="left" :text="getAllGrade()"></ZTooltip>
          </a-col>
        </a-row>
        <!--  选择选项估价-->
        <div style="height: 400px;overflow: auto;min-width: 456px">
          <a-collapse v-model:activeKey="evaluateData.activeKey" accordion>
            <a-collapse-panel v-for="(q,index) in evaluateData.collapsePanelList" :key="index">
              <!--        折叠面板标题-->
              <template #header>
                <div style="display: flex;flex-direction: row;justify-content: space-between;width: 100%">
                  <span style="display: inline-block;max-width: 200px;text-overflow: ellipsis;;white-space: nowrap;overflow-x: hidden">{{ `${index + 1}.${q.questionName}` }}</span>
                  <ZTooltip v-if="q.selectType===0" :display="'inline-block'" :text="getOptionName(q.options,q.selectedOptionId)"></ZTooltip>
                  <ZTooltip v-if="q.selectType===1" :display="'inline-block'" :text="getOptionsName(q.options,q.selectedOptionIds)"></ZTooltip>
                </div>
              </template>
              <!--        多选-->
              <a-checkbox-group v-if="q.selectType===1"
                                v-model:value="q.selectedOptionIds"
                                style="width: 100%" @change="multipleOptionChange(q.options,q.selectedOptionIds,index)">
                <div v-for="o in q.options">
                  <a-checkbox :disabled="o.choosable===0" :value="o.id">
                    <ZTooltip max-width="350px" text-align="left" :text="`${o.optionName} 成色(${formatQuestionInfo('grade',o.grade)})`"></ZTooltip>
                    <ZTooltip max-width="350px" text-align="left" :tColor="'#ff0000'" v-if="o.choosable===0" :text="`(不可选理由：${o.reason})`"></ZTooltip>
                  </a-checkbox>
                </div>
              </a-checkbox-group>
              <!--        单选-->
              <a-radio-group v-if="q.selectType===0"
                             v-model:value="q.selectedOptionId"
                             style="width: 100%" @change="singleOptionChange(q.options,q.selectedOptionId,index)">
                <div v-for="o in q.options">
                  <a-radio :disabled="o.choosable===0" :value="o.id">
                    <ZTooltip max-width="350px" text-align="left" :text="`${o.optionName} 成色(${formatQuestionInfo('grade',o.grade)})`"></ZTooltip>
                    <ZTooltip max-width="350px" text-align="left" :tColor="'#ff0000'" v-if="o.choosable===0" :text="`(不可选理由：${o.reason})`"></ZTooltip>
                  </a-radio>
                </div>
              </a-radio-group>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>

import {orderApi} from "/@/views/business/order/order";
import {reactive, ref} from "vue";
import {modelEvaluateApi} from "/@/views/business/evaluate/model-evaluate/model-evaluate";
import {formatQuestionInfo} from "/@/views/business/evaluate/question/question-api";
import _ from 'lodash';
import ZTooltip from "/@/views/support/common-component/z-tooltip.vue";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {smartSentry} from "/@/lib/smart-sentry";
import {modelApi} from "/@/views/business/data-config/model/model-api";
const modalRef = ref();
const modalData = reactive({
  visible: false,
  top: 100,
  left: 100,
  startTop: 0,
  startLeft: 0,
})
const evaluateDetail = reactive({
  modelName: undefined,
  mrp: undefined,
  evalContent: []
});
const isMove = ref(false);

const brandOptions = ref([]);
const modelOptions = ref([]);
const orderDetail = reactive({});

const evaluateDataDefault = {
  evaluateId: undefined,
  brandId: undefined,
  category: undefined,
  modelId: undefined,
  appraiseValue: 0,
  activeKey: 0,
  visible: false,
  detail: {},
  collapsePanelList: [],
};
const evaluateData = reactive({...evaluateDataDefault});

document.addEventListener('mouseup', function () {
  mouseMoveEnd();
})
document.addEventListener('mousemove', function (e) {
  mouseMove(e);
})

// 查询品牌
async function queryBrand() {
  try {
    let responseModel = await brandApi.queryPage({pageNum: 1, pageSize: 200});
    brandOptions.value = responseModel.data.list;
    console.log(brandOptions.value)
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 查询型号
async function queryModel() {
  evaluateData.modelId = undefined;
  evaluateData.collapsePanelList = [];
  Object.assign(evaluateData.detail, {});
  try {
    let responseModel = await modelApi.queryPage({
      brandId: evaluateData.brandId,
      category: evaluateData.category,
      pageNum: 1, pageSize: 200
    });
    modelOptions.value = responseModel.data.list;
  } catch (e) {
    smartSentry.captureError(e);
  }
}
async function modelChange(e) {
  console.log(e)
  evaluateData.appraiseValue = 0;
  evaluateData.activeKey = 0;
  evaluateData.collapsePanelList = [];
  if (!e){
    modelOptions.value = [];
    Object.assign(evaluateData.detail, {});
    queryModel();
    return;
  }
  const {data} = await modelEvaluateApi.detailById(e);
  data.questionContext = JSON.parse(data.questionContext);
  Object.assign(evaluateData.detail, data);
  evaluateData.collapsePanelList[0] = getDetailClone().questionContext[0];
  console.log(data)
}
// 输入过滤型号
function filterModelOption(input, option) {
  return option.modelName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}
function mouseStart(e) {
  modalData.startTop = e.clientY - parseInt(getComputedStyle(modalRef.value)['top']);
  modalData.startLeft = e.clientX - parseInt(getComputedStyle(modalRef.value)['left']);
  isMove.value = true;
}

function mouseMove(e) {
  if (isMove.value) {
    modalData.top = e.clientY - modalData.startTop ;
    modalData.left =  e.clientX - modalData.startLeft ;
  }
}

function mouseMoveEnd() {
  isMove.value = false;
}

const props = defineProps(['orderId','modelId','orderDetail']);

async function showModal() {
  Object.assign(orderDetail,props.orderDetail);
  queryBrand();
  if (orderDetail.orderWay===1){
    orderApi.evaluateDetail(props.orderId).then(res => {
      Object.assign(evaluateDetail, res.data);
      console.log(res)
    })
  }
  evaluateData.modelId = props.modelId||undefined;
  if (evaluateData.modelId){
    const {data} = await modelEvaluateApi.detailById(evaluateData.modelId);
    data.questionContext = JSON.parse(data.questionContext);
    Object.assign(evaluateData.detail, data);
    evaluateData.collapsePanelList[0] = getDetailClone().questionContext[0];
    console.log(data)
  }

  let responseModel = await modelApi.queryPage({
    modelId: evaluateData.modelId, //型号id
    pageNum: 1,
    pageSize: 200,
  });
  const list = responseModel.data.list;
  modelOptions.value = list;

  modalData.visible = true;
}
function hideModal() {
  Object.assign(modalData, {
    visible: false,
    top: 100,
    left: 100,
    startTop: 0,
    startLeft: 0,
  });
  Object.assign(evaluateDetail, {
    modelName: undefined,
    mrp: undefined,
    evalContent: []
  });
  Object.assign(evaluateData, evaluateDataDefault);
  evaluateData.collapsePanelList = [];
}


function getOptionName(options, id) {
  let name = '';
  options.forEach(item => {
    if (item.id === id) {
      name = item.optionName;
    }
  })
  return name;
}

function getOptionsName(options, ids) {
  let list = [];
  if (ids && ids.length) {
    options.forEach(item => {
      if (ids.findIndex(i => i === item.id) !== -1) {
        list.push(item.optionName);
      }
    })
  }
  return list.join(',');
}

function getAllGrade(){
  const list = [];
  evaluateData.collapsePanelList.forEach(q=>{
    if (q?.selectedOptionIds&&q?.selectedOptionIds.length){
      q.options.forEach(item => {
        if (q?.selectedOptionIds.findIndex(i => i === item.id) !== -1) {
          list.push(formatQuestionInfo('grade',item.grade));
        }
      })
    }
    if (q?.selectedOptionId){

      q.options.forEach(item => {
        if (item.id === q?.selectedOptionId) {
          list.push(formatQuestionInfo('grade',item.grade));
        }
      })
    }
  });
  return list.join(',');
}

function multipleOptionChange(options, ids, index) {
  console.log(options, ids, index)
  evaluateData.appraiseValue = 0;
  evaluateSubmit();
}

function singleOptionChange(options, id, index) {
  let option = {};
  evaluateData.appraiseValue = 0;
  options.forEach(o => {
    if (o.id === id) {
      option = o;
    }
  });
  if (option.jump === 'jumpToNext') {
    if (index + 1 === evaluateData.collapsePanelList.length && evaluateData.collapsePanelList.length < evaluateData.detail.questionContext.length) {
      evaluateData.collapsePanelList[index + 1] = getDetailClone().questionContext[index + 1];
      evaluateData.activeKey = index + 1;
    }
  }
  if (option.jump === 'jumpToEnd') {
    evaluateData.collapsePanelList.splice(index + 1, evaluateData.collapsePanelList.length - (index + 1));
    evaluateData.activeKey = index;
  }
  evaluateSubmit();
}

async function evaluateSubmit() {
  const optionIds = [];
  evaluateData.collapsePanelList.forEach(q => {
    if (q?.selectedOptionId) {
      optionIds.push(q?.selectedOptionId);
    }
    if (q?.selectedOptionIds) {
      optionIds.push(...q?.selectedOptionIds);
    }
  });
  console.log(evaluateData)
  const {data} = await modelEvaluateApi.appraise(evaluateData.detail.id, {optionIds: optionIds.join(',')});
  evaluateData.appraiseValue = data;
}

function getDetailClone() {
  return _.cloneDeep(evaluateData.detail);
}

defineExpose({
  showModal,
});

</script>

<style lang="less" scoped>
::-webkit-scrollbar{
  width: 0 !important;
  display: none !important;
}
.row {
  margin-bottom: 8px;
  align-items: center;

  .rowLabel {
    text-align: right;
    padding-right: 8px;
    .req {
      color: red;
    }
  }
}
</style>